<template>
  <transition name="message_fade">
    <div
      :class="styleClass"
      v-show="visible"
      :style="{
        top: top + 'px',
      }"
    >
      {{ message }}
    </div>
  </transition>
</template>

<script setup>
import types from "./types";
import { computed, reactive, toRefs } from "vue";
let t = null;
const state = reactive({
  visible: false,
  top: 20,
});
const { visible, top } = toRefs(state);
const props = defineProps({
  type: {
    type: String,
    default: types.MESSAGE,
    validator: (val) => {
      return Object.values(types).includes(val);
    },
  },
  message: {
    type: String,
    default: "",
  },
  duration: {
    type: Number,
    default: 3000,
  },
});
const styleClass = computed(() => ["jspp_message", props.type]);
const setVisible = async (status) => {
  return new Promise((resolve) => {
    state.visible = status;
    t = setTimeout(() => {
      clearTimeout(t);
      t = null;
      resolve();
    }, 300);
  });
};

const setTop = (t) => {
  state.top = t;
  return t;
};

defineExpose({
  setVisible,
  setTop,
  height: 40,
  margin: 20,
});
</script>

<style lang="scss" scoped>
.message_fade-enter-from,
.message_fade-leave-to {
  transform: translateY(-20px);
  opacity: 0;
}
.message_fade-enter-active {
  transition: all 0.3s ease-in;
}
.message_fade-leave-active {
  transition: all 0.3s ease-out;
}
.jspp_message {
  position: fixed;
  left: 50%;
  width: 380px;
  height: 40px;
  line-height: 40px;
  z-index: 1000;
  margin-left: -190px;
  text-align: center;
  font-size: 16px;
  border-radius: 9px;
  color: white;
  transition: all 0.3s ease-out;
  &.success {
    background: green;
  }
  &.warning {
    background: orange;
  }
  &.error {
    background: rgb(221, 115, 115);
  }
  &.message {
    background: grey;
  }
}
</style>
